package com.zbcx.generate.mbtiles;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

import com.zbcx.generate.mbtiles.db.DBUtils;
import com.zbcx.generate.mbtiles.db.TransactionManager;

/**
 * 遍历所有文件夹 <br/>
 * 生成mbtiles
 * 
 * @author zbcx
 * 
 */
public class GenerateMbtiles {

	private JButton open;
	private ExecutorService fixedThreadPool;

	public void listPathFiles(JButton open, String filePath) {
		fixedThreadPool = Executors.newFixedThreadPool(200);

		this.open = open;
		List<File> file = listPathFiles(filePath);

		if (file.size() > 0) {
			open.setText("你选择的目录不符合规范");
			return;
		}
		String[] dbPath = DBUtils.URL.split("//");
		open.setText("你生成的目录在：" + dbPath[dbPath.length - 1]);
	}

	/**
	 * wms目录 输出wms所有文件夹 输出所有级数
	 * 
	 * @param root
	 * @return
	 */
	public List<File> listPathFiles(String root) {
		List<File> allDir = new ArrayList<File>();
		File path = new File(root);
		File[] files = path.listFiles();
		for (File f : files) {
			if (f.isFile())
				allDir.add(f);
			else
				listPath(f.getAbsolutePath());
		}
		return allDir;
	}

	/**
	 * 0级目录下输出 0级中的所有文件夹 输出所有行数
	 * 
	 * @param path
	 * @return 绝对路径
	 */
	public List<String> listPath(String root) {
		List<String> allDir = new ArrayList<String>();
		File path = new File(root);
		if (path.isDirectory()) {
			for (File f : path.listFiles()) {
				if (f.isDirectory() && !f.getName().startsWith(".")) {
					outFolder(f.getAbsolutePath());
				}
			}
		}
		return allDir;
	}

	/**
	 * 遍历行号下所有的文件
	 * 
	 * @param fileRootPath
	 */
	public void outFolder(String fileRootPath) {
		System.out.println("文件夹：" + fileRootPath);

		final String[] spPath = fileRootPath.split("\\\\");

		File imgFile = new File(fileRootPath);
		File[] files = imgFile.listFiles();
		for (final File file : files) {
			if (file.isFile()) {
//				fixedThreadPool.execute(new Runnable() {
//					public void run() {
						try {
							TransactionManager.beginTransaction();

							DBUtils.insert(
									file,
									Integer.parseInt(spPath[spPath.length - 2]),
									Integer.parseInt(spPath[spPath.length - 1]),
									Integer.parseInt(getFileNameNoEx(file
											.getName())));
							TransactionManager.commit();
						} catch (Exception e) {
							e.printStackTrace();
						}

//					}
//				});

			}
		}
	}

	/**
	 * 获取不带扩展名的文件名
	 * 
	 * @param filename
	 * @return
	 */
	public String getFileNameNoEx(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length()))) {
				return filename.substring(0, dot);
			}
		}
		return filename;
	}
}
